package com.ktjiaoyu.config;

import com.ktjiaoyu.cond.ConblePropertyEnaable;
import org.apache.commons.dbcp2.BasicDataSource;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.*;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
import java.io.IOException;

@Configuration
@PropertySource("classpath:database.properties")
public class MyBatisConfig {

    @Value("${jdbc.driver}")
    private String driverClassName;

    @Value("${jdbc.url}")
    private String url;

    @Value("${jdbc.username}")
    private String username;

    @Value("${jdbc.password}")
    private String password;

    @Value("${pool.initialSize}")
    private int initialSize;

    @Value("${pool.maxTotal}")
    private int maxTotal;

    @Value("${pool.maxIdle}")
    private int maxIdle;

    @Value("${pool.minIdle}")
    private int minIdle;

    // 1. 开发环境数据源（dev.enable=true 时生效）
    @Bean(name = "dataSource")
    @Conditional(ConblePropertyEnaable.OnEnableCondition.class)
    @ConblePropertyEnaable(enableProperty = "dev.enable")
    public DataSource dataSource() {
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName(driverClassName);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        dataSource.setInitialSize(initialSize);
        dataSource.setMaxTotal(maxTotal);
        dataSource.setMaxIdle(maxIdle);
        dataSource.setMinIdle(minIdle);
        dataSource.setTestOnBorrow(true);
        dataSource.setValidationQuery("SELECT 1");
        return dataSource;
    }

    // 2. 测试环境数据源（test.enable=true 时生效）
    @Bean(name = "testDataSource")
    @Conditional(ConblePropertyEnaable.OnEnableCondition.class)
    @ConblePropertyEnaable(enableProperty = "test.enable")
    public DataSource testDataSource() {
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/test_db");
        dataSource.setUsername("root");
        dataSource.setPassword("root1123");
        dataSource.setInitialSize(5);
        dataSource.setMaxTotal(10);
        dataSource.setMaxIdle(5);
        dataSource.setMinIdle(2);
        return dataSource;
    }

    // 3. SqlSessionFactoryBean，动态选择数据源
    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(
            @Autowired(required = false) @Qualifier("dataSource") DataSource dataSource,
            @Autowired(required = false) @Qualifier("testDataSource") DataSource testDataSource
    ) throws IOException {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();

        // 动态选择数据源（优先使用 testDataSource，如果不存在则用 dataSource）
        DataSource targetDataSource = (testDataSource != null) ? testDataSource : dataSource;
        if (targetDataSource == null) {
            throw new IllegalStateException("No DataSource available! Check dev.enable or test.enable.");
        }

        sqlSessionFactoryBean.setDataSource(targetDataSource);
        sqlSessionFactoryBean.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml")
        );
        sqlSessionFactoryBean.setTypeAliasesPackage("com.ktjiaoyu.entity");
        return sqlSessionFactoryBean;
    }
}